package bb.lanxing.lib.devices.base;

import java.util.List;
import java.util.ListIterator;

import android.content.Context;
import android.content.Intent;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;

import bb.lanxing.lib.devices.antplus.AntPlusCadence;
import bb.lanxing.lib.devices.antplus.AntPlusHearRate;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.PeerDevice;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.bici.BICIDevice;
import bb.lanxing.lib.devices.bici.BiciController;
import bb.lanxing.lib.devices.ble.BleCons;
import bb.lanxing.lib.devices.ble.battery.BatteryController;
import bb.lanxing.lib.devices.ble.device.BesDevice;
import bb.lanxing.lib.devices.ble.device.Cadence01Device;
import bb.lanxing.lib.devices.ble.device.HeartRate01Device;
import bb.lanxing.lib.devices.ble.device.LightDevice;
import bb.lanxing.lib.devices.ble.device.RadarDevice;
import bb.lanxing.lib.devices.ble.device.SmartAssistDevice;
import bb.lanxing.lib.devices.ble.device.StandardBiketrainerDevice;
import bb.lanxing.lib.devices.ble.device.StandardCadenceDevice;
import bb.lanxing.lib.devices.ble.device.StandardCrosstrainerDevice;
import bb.lanxing.lib.devices.ble.device.StandardHeartrateBeltDevice;
import bb.lanxing.lib.devices.ble.device.StandardHeartrateDevice;
import bb.lanxing.lib.devices.ble.device.StandardIndoorbikeDevice;
import bb.lanxing.lib.devices.ble.device.StandardPowerrateDevice;
import bb.lanxing.lib.devices.ble.device.StandardRowerDevice;
import bb.lanxing.lib.devices.ble.device.SwitchableCadenceSpeedDevice;
import bb.lanxing.lib.devices.ble.device.X1Client;
import bb.lanxing.lib.devices.ble.device.XossSGDevice;
import bb.lanxing.lib.devices.ble.heartrate.HeartRateBeltController;
import bb.lanxing.lib.devices.ble.light.LightDeviceController;
import bb.lanxing.lib.devices.ble.switchablecadence.SwitchableCadenceController;
import bb.lanxing.lib.devices.ble.x1.X1Controller;
import bb.lanxing.lib.devices.cad01.Cadence01Controller;
import bb.lanxing.lib.devices.core.AbstractDeviceManager;
import bb.lanxing.lib.devices.core.ble.AbsBleDevice;
import bb.lanxing.lib.devices.core.ble.SpecificationAttributes;
import bb.lanxing.lib.devices.core.dfu.IDfuAdapter;
import bb.lanxing.lib.devices.core.dfu.IDfuDevice;
import bb.lanxing.lib.devices.core.utils.CharacteristicValueHelper;
import bb.lanxing.lib.devices.heartrate01.HeartRate01Controller;
import bb.lanxing.lib.devices.sprint.XossDeviceController;
import bb.lanxing.lib.devices.utils.AntPlusUtils;
import bb.lanxing.lib.devices.utils.ConnectionStateReceiver;
import bb.lanxing.lib.devices.utils.DeviceActionReceiver;
import bb.lanxing.lib.devices.utils.DeviceUtils;

public abstract class AbstractXZDeviceManager extends AbstractDeviceManager
        implements XZDeviceManager, ConnectionListener {
    private DeviceActionReceiver mActionReceiver;
    private ConnectionStateReceiver mStateReceiver;

    @Override
    protected void d(String str) {
    }

    protected boolean isGlobalListenerEnabled() {
        return false;
    }

    @Override
    protected boolean isSupportedDevice(int i) {
        return false;
    }

    @Override
    public void onConfigHeartRate(boolean z, int i) {
    }

    protected boolean shouldPublishDeviceStatus() {
        return false;
    }

    @Override
    public void startAndRefreshAutoConnector() {
        d("connect to bound devices");
    }

    @Override
    public void stopAutoConnector() {
        d("stop autoConnector to bound devices");
    }

    @Override
    public synchronized PeerDevice createDeviceIfNeed(SmartDevice smartDevice) {
        PeerDevice deviceByAddress;
        deviceByAddress = getDeviceByAddress(smartDevice.getAddress());
        if (deviceByAddress == null) {

            int protocol = smartDevice.getProtocol() == 0 ? 1 : smartDevice.getProtocol();
            if (protocol == SmartDevice.PROTOCOL_BLE) {
                Log.d("wangsm_bt", " createDeviceIfNeed -> createBleDeviceIfNeed");
                deviceByAddress = createBleDeviceIfNeed(smartDevice);
            } else if (protocol == SmartDevice.PROTOCOL_ANT_PLUS) {
                Log.d("wangsm_bt", " createDeviceIfNeed -> createAntDeviceIfNeed");
                deviceByAddress = createAntDeviceIfNeed(smartDevice);
            }
            if (deviceByAddress != null) {
                addPeerDevice(deviceByAddress);
                deviceByAddress.registerConnectionListener(this);
            } else {
                Log.d("wangsm_bt", " createDeviceIfNeed ->  deviceByAddress is null");
            }
        }
        Log.d("wangsm_bt", " createDeviceIfNeed -> return deviceByAddress");
        return deviceByAddress;
    }

    private synchronized PeerDevice createAntDeviceIfNeed(SmartDevice smartDevice) {
        Context context = getContext();
        if (context != null && AntPlusUtils.isAntPlusAvailable(context)) {
            PeerDevice deviceByAddress = getDeviceByAddress(smartDevice.getAddress());
            if (deviceByAddress != null) {
                return deviceByAddress;
            }
            int type = smartDevice.getType();
            if (type == SmartDevice.TYPE_CADENCE) {
                deviceByAddress = new AntPlusCadence(context, smartDevice);
            } else if (type == SmartDevice.TYPE_HEARTRATE) {
                deviceByAddress = new AntPlusHearRate(context, smartDevice);
            }
            return deviceByAddress;
        }
        return null;
    }

    private synchronized PeerDevice createBleDeviceIfNeed(SmartDevice smartDevice) {
        Context context = getContext();
        if (context != null && smartDevice != null && !TextUtils.isEmpty(smartDevice.getAddress())) {
            PeerDevice deviceByAddress = getDeviceByAddress(smartDevice.getAddress());
            if (deviceByAddress != null) {
                return deviceByAddress;
            }

            d("Create device for: " + smartDevice.getName());
            int type = smartDevice.getType();
            Log.d("wangsm_bt", " create Ble device begin ,type: " + type);
            if (type == SmartDevice.TYPE_BES) {
                deviceByAddress = new BesDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_BICI) {
                deviceByAddress = new BICIDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_CADENCE) {
                deviceByAddress = new StandardCadenceDevice(context, smartDevice);
                // } else if (smartDevice.getName().toLowerCase().contains("xoss")) {//delete, not used
                // deviceByAddress = new StandardHeartrateBeltDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_HEARTRATE) {
                deviceByAddress = new StandardHeartrateDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_BIKE_TRAINER) {
                deviceByAddress = new StandardBiketrainerDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_POWERRATE) {
                deviceByAddress = new StandardPowerrateDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_INDOOR_BIKE) {
                deviceByAddress = new StandardIndoorbikeDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_CROSS_TRAINER) {
                deviceByAddress = new StandardCrosstrainerDevice(context, smartDevice);
            } else if (type == SmartDevice.TYPE_ROWER) {
                deviceByAddress = new StandardRowerDevice(context, smartDevice);
            }else {
                if (type == SmartDevice.TYPE_X1) {
                    deviceByAddress = new X1Client(context, smartDevice);
                } else if (type == SmartDevice.TYPE_Q1) {
                    deviceByAddress = new SmartAssistDevice(context, smartDevice);
                } else if (type == SmartDevice.TYPE_WINGS || type == SmartDevice.TYPE_DISCOVERY
                        || type == SmartDevice.TYPE_IGPS || type == SmartDevice.TYPE_BRYTEN) {
                    // deviceByAddress = new XOSSFGDevice(getContext(), smartDevice, getWorkDir(smartDevice.getType()));
                } else {
                    switch (type) {
                    case SmartDevice.TYPE_HEARTRATE_BELT ->
                        deviceByAddress = new StandardHeartrateBeltDevice(context, smartDevice);
                    // case SmartDevice.TYPE_XOSS_G -> {
                    // }
                    case SmartDevice.TYPE_RADAR_SR -> deviceByAddress = new RadarDevice(context, smartDevice);
                    case SmartDevice.TYPE_VORTEX_CADENCE ->
                        deviceByAddress = new SwitchableCadenceSpeedDevice(context, smartDevice);
                    case SmartDevice.TYPE_CADENCE01 ->
                        deviceByAddress = new Cadence01Device(context, smartDevice);
                    case SmartDevice.TYPE_XOSS_NAV ->
                        deviceByAddress = new XossSGDevice(context, smartDevice, getWorkDir(SmartDevice.TYPE_XOSS_NAV));
                    // case SmartDevice.TYPE_HR_X2_PRO ->
                    // new XossHeartrateX2ProDevice(context, smartDevice, getWorkDir(SmartDevice.TYPE_HR_X2_PRO));
                    case SmartDevice.TYPE_LIGHT -> new LightDevice(smartDevice);
                    case SmartDevice.TYPE_HEART_RATE01 ->
                         deviceByAddress = new HeartRate01Device(context, smartDevice);
                    default -> {
                    }
                    }
                }
            }
            return deviceByAddress;
        }
        return null;
    }

    @Override
    public String getWorkDir(int i) {
        return DeviceContext.getDeviceConfiguration().getRootDir(i);
    }

    @Override
    public XossDeviceController getXossDeviceController(String address) {
        SmartDevice deviceByAddress;
        PeerDevice deviceByAddress2 = getDeviceByAddress(address);
        if (deviceByAddress2 == null && (deviceByAddress = DeviceContext.getDeviceByAddress(address)) != null) {
            deviceByAddress2 = createDeviceIfNeed(deviceByAddress);
        }
        if (!(deviceByAddress2 instanceof XossDeviceController)) {
            return null;
        }
        return (XossDeviceController) deviceByAddress2;
    }

    @Override
    public XossDeviceController getXossDeviceController(String address, String name, int i) {
        if (address == null) {
            // Log.d("wangsm_bt"," ,getXossDeviceController the address is null,return null");
            return null;
        }
        PeerDevice deviceByAddress = getDeviceByAddress(address);
        if (deviceByAddress == null) {
            // Log.d("wangsm_bt"," ,getXossDeviceController deviceByAddress is null,create it");
            SmartDevice create = DeviceContext.getDeviceProvider().create();
            create.setName(name);
            create.setAddress(address);
            create.setType(i);
            // Log.d("wangsm_bt"," ,getXossDeviceController SmartDevice setType i:" + i);
            create.setProtocol(SmartDevice.PROTOCOL_BLE);
            deviceByAddress = createDeviceIfNeed(create);
        }
        if (deviceByAddress instanceof XossDeviceController) {
            // Log.d("wangsm_bt"," ,getXossDeviceController return deviceByAddress");
            return (XossDeviceController) deviceByAddress;
        }

        // Log.d("wangsm_bt"," ,getXossDeviceController return null");
        return null;
    }

    @Override
    public X1Controller getX1Controller(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof X1Client)) {
            return null;
        }
        return (X1Controller) deviceByAddress;
    }

    @Override
    public HeartRateBeltController getHeartRateBeltController(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof StandardHeartrateBeltDevice)) {
            return null;
        }
        return (HeartRateBeltController) deviceByAddress;
    }

    @Override
    public SwitchableCadenceController getSwitchableCadenceController(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof SwitchableCadenceSpeedDevice)) {
            return null;
        }
        return (SwitchableCadenceController) deviceByAddress;
    }
    @Override
    public Cadence01Controller getCadence01Controller(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof Cadence01Device)) {
            return null;
        }
        return (Cadence01Controller) deviceByAddress;
    }

    @Override
    public HeartRate01Controller getHeartRate01Controller(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof HeartRate01Device)) {
            return null;
        }
        return (HeartRate01Controller) deviceByAddress;
    }

    @Override
    public LightDeviceController getLightDeviceController(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof LightDeviceController)) {
            return null;
        }
        return (LightDeviceController) deviceByAddress;
    }

    @Override
    public BatteryController getBatteryController(String str) {
        PeerDevice deviceByAddress = getDeviceByAddress(str);
        if (!(deviceByAddress instanceof BatteryController)) {
            return null;
        }
        return (BatteryController) deviceByAddress;
    }

    @Override
    public BiciController getBiciController(String str) {
        BICIDevice bICIDevice = (BICIDevice) getDeviceByAddress(str);
        SmartDevice deviceByAddress = DeviceContext.getDeviceByAddress(str);
        if (bICIDevice == null && deviceByAddress != null) {
            bICIDevice = (BICIDevice) createBleDeviceIfNeed(deviceByAddress);
        }
        if (bICIDevice != null) {
            return bICIDevice.getController();
        }
        return null;
    }

    @Override
    public void connect(SmartDevice smartDevice) {
        super.connect(smartDevice);
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int newState, int errorCode) {
        super.notifyStateChanged(smartDevice, newState, errorCode);
        if (shouldPublishDeviceStatus()) {
            notifyStateChangedByBroadcast(smartDevice, newState, errorCode);
        }
    }

    private void disconnectOtherDevices(SmartDevice smartDevice) {
        List<PeerDevice> connectedDevicesByType = getConnectedDevicesByType(smartDevice.getType());
        String address = smartDevice.getAddress();
        ListIterator<PeerDevice> listIterator = connectedDevicesByType.listIterator();
        while (listIterator.hasNext()) {
            if (address.equals(listIterator.next().getAddress())) {
                listIterator.remove();
            }
        }
        if (DeviceUtils.isDualModeDevice(smartDevice.getName())) {
            ListIterator<PeerDevice> listIterator2 = connectedDevicesByType.listIterator();
            while (true) {
                if (listIterator2.hasNext()) {
                    if (DeviceUtils.isDualModeDevice(listIterator2.next().getName())) {
                        listIterator2.remove();
                        break;
                    }
                } else {
                    break;
                }
            }
        }
        for (PeerDevice peerDevice : connectedDevicesByType) {
            peerDevice.close();
            removeDeviceByAddress(peerDevice.getAddress());
        }
        if (smartDevice.getType() == SmartDevice.TYPE_CADENCE) {
            if (isConnected(SmartDevice.TYPE_Q1)) {
                disconnect(SmartDevice.TYPE_Q1);
            }
        } else if (smartDevice.getType() == SmartDevice.TYPE_Q1 && isConnected(SmartDevice.TYPE_CADENCE)) {
            disconnect(SmartDevice.TYPE_CADENCE);
        }
    }

    @Override
    public void registerConnectionStateListener(ConnectionListener connectionListener) {
        super.registerConnectionStateListener(connectionListener);
        Context context = getContext();
        synchronized (this) {
            if (this.mStateReceiver == null && isGlobalListenerEnabled() && context != null) {
                ConnectionStateReceiver connectionStateReceiver = new ConnectionStateReceiver();
                this.mStateReceiver = connectionStateReceiver;
                connectionStateReceiver.register(getContext(), new ConnectionListener() {
                    @Override
                    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
                        AbstractXZDeviceManager.this.notifyStateChanged(smartDevice, i, i2);
                    }
                });
            }
        }
    }

    @Override
    public void unregisterConnectionStateListener(ConnectionListener connectionListener) {
        ConnectionStateReceiver connectionStateReceiver;
        super.unregisterConnectionStateListener(connectionListener);
        synchronized (this) {
            if (getConnectionStateNotifier().isEmpty() && (connectionStateReceiver = this.mStateReceiver) != null) {
                connectionStateReceiver.unregister(getContext());
                this.mStateReceiver = null;
            }
        }
    }

    protected void notifyStateChangedByBroadcast(SmartDevice smartDevice, int i, int i2) {
        Context context = getContext();
        if (context == null || !shouldPublishDeviceStatus()) {
            return;
        }
        Intent intent = new Intent(ConnectionStateReceiver.ACTION_CONNECTION_STATE_CHANGE);
        intent.putExtra(ConnectionStateReceiver.EXTRA_CONNECTION_STATE, i);
        intent.putExtra(ConnectionStateReceiver.EXTRA_SMART_DEVICE, smartDevice);
        intent.putExtra(ConnectionStateReceiver.EXTRA_CONNECTION_ERROR, i2);
        intent.setPackage(context.getPackageName());
        context.sendBroadcast(intent);
    }

    public void registerActionReceiver() {
        if (this.mActionReceiver == null) {
            this.mActionReceiver = new DeviceActionReceiver() {
                @Override
                protected boolean handleBroadcast(Intent intent) {
                    return AbstractXZDeviceManager.this.handleDeviceAction(intent);
                }
            };
        }
        unregisterActionReceiver();
        this.mActionReceiver.registerReceiver(getContext());
    }

    protected void unregisterActionReceiver() {
        DeviceActionReceiver deviceActionReceiver = this.mActionReceiver;
        if (deviceActionReceiver != null) {
            deviceActionReceiver.unregisterReceiver(getContext());
        }
    }

    public boolean handleDeviceAction(Intent intent) {
        X1Controller x1Controller;
        String action = intent.getAction();
        int intExtra = intent.getIntExtra(BleCons.EXTRA_DEVICE_TYPE, 0);
        String stringExtra = intent.getStringExtra(BleCons.EXTRA_DEVICE_ADDRESS);
        Log.d("wangsm_bt", " AbstractXZDevviceManager address $stringExtra");
        if (stringExtra == null) {
            stringExtra = intent.getStringExtra(CharacteristicValueHelper.EXTRA_ADDRESS);
        }
        PeerDevice deviceByType = TextUtils.isEmpty(stringExtra) ? getDeviceByType(SmartDevice.TYPE_BICI, intExtra)
                : getDeviceByAddress(stringExtra);
        if (deviceByType == null) {
            return false;
        }
        if (action == null) {
            return false;
        }
        switch (action) {
        case BleCons.ACTION_REQUEST_DEVICE_INFORMATION -> {
            if (deviceByType instanceof AbsBleDevice absBleDevice) {
                absBleDevice.readFirmwareVersion();
                absBleDevice.readModel();
                absBleDevice.readManufacturer();
            }
        }
        case BleCons.ACTION_HEARTRATE_BODY_LOCATION -> {
            if (deviceByType instanceof AbsBleDevice) {
                ((AbsBleDevice) deviceByType).readHeartRateBodyLocation();
            }
        }
        case BleCons.ACTION_ACTION_SEND_CMD -> {
            int intExtra2 = intent.getIntExtra(BleCons.EXTRA_X1_UNIT, 1);
            float floatExtra = intent.getFloatExtra(BleCons.EXTRA_X1_PERIMETER, 0.0f);
            int intExtra3 = intent.getIntExtra(BleCons.EXTRA_X1_WEIGHT, 0);
            if (isConnected(stringExtra) && (x1Controller = getX1Controller(stringExtra)) != null) {
                x1Controller.set(intExtra3, floatExtra, intExtra2);
            }
        }
        case BleCons.ACTION_READ_DEVICE_INFORMATION -> {
            if (deviceByType instanceof AbsBleDevice absBleDevice2) {
                Intent intent2 = new Intent(BleCons.ACTION_READ_DEVICE_INFORMATION_RESULT);
                intent2.putExtra(BleCons.EXTRA_DEVICE_TYPE, deviceByType.getType());
                intent2.putExtra(BleCons.EXTRA_BATTERY, absBleDevice2.getBattery());
                intent2.putExtra(BleCons.EXTRA_MANUFACTURE, absBleDevice2.getManufacturer());
                intent2.putExtra(BleCons.EXTRA_MODEL, absBleDevice2.getModel());
                intent2.putExtra(BleCons.EXTRA_FIRMWARE_VERSION, absBleDevice2.getFirmwareVersion());
                intent2.putExtra(BleCons.EXTRA_SERIAL, absBleDevice2.getSerial());
                intent2.putExtra(BleCons.EXTRA_HARDWARE_VERSION, absBleDevice2.getHardwareVersion());
                intent2.putExtra(BleCons.EXTRA_DEVICE_NAME, absBleDevice2.getName());
                intent2.setPackage(DeviceContext.getApplicationContext().getPackageName());
                getContext().sendBroadcast(intent2);
            }
        }
        case BleCons.ACTION_REQUEST_BATTERY -> {
            if (deviceByType instanceof AbsBleDevice) {
                ((AbsBleDevice) deviceByType).readBattery();
            }
        }
        case IDfuAdapter.ACTION_DFU_MODE_SETUP -> {
            int intExtra4 = intent.getIntExtra(IDfuAdapter.EXTRA_DFU_MODE_STATE, 4);
            if (deviceByType instanceof IDfuDevice) {
                IDfuAdapter dfuAdapter = ((IDfuDevice) deviceByType).getDfuAdapter();
                if (intExtra4 == 2) {
                    dfuAdapter.enterDfuMode();
                }
            }
        }
        case CharacteristicValueHelper.ACTION_READ_CHARACTERISTIC -> {
            if (deviceByType instanceof AbsBleDevice absBleDevice3) {
                ParcelUuid parcelUuid = intent.getParcelableExtra(CharacteristicValueHelper.EXTRA_UUID);
                if (parcelUuid != null) {
                    if (SpecificationAttributes.BLE_DEVICE_INFORMATION_SOFTWARE_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readSoftwareVersion();
                    } else if (SpecificationAttributes.BLE_DEVICE_INFORMATION_FIRMWARE_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readFirmwareVersion();
                    } else if (SpecificationAttributes.BLE_BATTERY_CHARACTERISTIC.equals(parcelUuid.getUuid())) {
                        absBleDevice3.readBattery();
                    } else if (SpecificationAttributes.BLE_DEVICE_INFORMATION_MANUFACTURER_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readManufacturer();
                    } else if (SpecificationAttributes.BLE_DEVICE_INFORMATION_MODEL_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readModel();
                    } else if (SpecificationAttributes.BLE_DEVICE_INFORMATION_SERIAL_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readSerial();
                    } else if (SpecificationAttributes.BLE_DEVICE_INFORMATION_HARDWARE_CHARACTERISTIC
                            .equals(parcelUuid.getUuid())) {
                        absBleDevice3.readHardware();
                    }
                }
            }
        }
        }
        return isSupportedDevice(intExtra);
    }

    @Override
    public void release() {
        AutoConnector.Companion.getInstance().stop();
        unregisterActionReceiver();
        super.release();
    }
}
